package cn.itsource.util;

import cn.itsource.domain.Course;
import cn.itsource.mapper.CourseMapper;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * excel导入
 */
public class DataListener extends AnalysisEventListener<Course> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;


    private CourseMapper courseMapper;

    public DataListener(CourseMapper courseMapper){
        this.courseMapper = courseMapper;
    }

    List<Course> list = new ArrayList<Course>();

    //读取数据会执行这方法
    @Override
    public void invoke(Course course, AnalysisContext analysisContext) {
        System.out.println(JSON.toJSONString(course));
        list.add(course);
        System.out.println(list);
        if (list.size() >= BATCH_COUNT){
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        System.out.println("所有数据解析完成");
    }

    private void saveData(){
        System.out.println(this.courseMapper);
        System.out.println("{" + list.size() + "}条数据，开始存储数据库" );
        for (Course course : list) {
            courseMapper.add(course);
        }
        System.out.println("存储数据库成功");
    }
}
